/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package programs;

import avenue.Session;
import javax.persistence.EntityManager;
import javax.swing.JOptionPane;
import model.Program;
import model.ProgramRate;
import model.RolePermission;

/**
 *
 * @author tasos
 */
public class ProgramsList extends javax.swing.JInternalFrame {

    /**
     * Creates new form ProgramsList
     */
    public ProgramsList() {
        em = Session.emf.createEntityManager();
        em.getTransaction().begin();
        initComponents();
        RolePermission rp = Session.GetPermission(Session.PROGRAMS_MODULE);
        this.NewProgram.setEnabled(rp.getCanCreate());
        this.EditProgram.setEnabled(rp.getCanUpdate());
        this.DeleteProgram.setEnabled(rp.getCanDelete());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        programQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("select p from Program p");
        programList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(programQuery.getResultList());
        jScrollPane1 = new javax.swing.JScrollPane();
        programTable = new javax.swing.JTable();
        NewProgram = new javax.swing.JButton();
        DeleteProgram = new javax.swing.JButton();
        EditProgram = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();

        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Συνδρομητικά Προγράμματα");
        setPreferredSize(new java.awt.Dimension(600, 400));

        programTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, programList, programTable, "ProgramBind");
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${name}"));
        columnBinding.setColumnName("Name");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${description}"));
        columnBinding.setColumnName("Description");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(programTable);

        NewProgram.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/add.gif"))); // NOI18N
        NewProgram.setText("Νέο");
        NewProgram.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                NewProgramActionPerformed(evt);
            }
        });

        DeleteProgram.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/remove.gif"))); // NOI18N
        DeleteProgram.setText("Διαγραφή");
        DeleteProgram.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DeleteProgramActionPerformed(evt);
            }
        });

        EditProgram.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/edit1.png"))); // NOI18N
        EditProgram.setText("Επεξεργασία");
        EditProgram.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                EditProgramActionPerformed(evt);
            }
        });

        cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        cancelButton.setText("Ακύρωση");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        saveButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/save.gif"))); // NOI18N
        saveButton.setText("Αποθήκευση");
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(NewProgram)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(DeleteProgram)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(EditProgram)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 63, Short.MAX_VALUE)
                        .addComponent(cancelButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(saveButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 312, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(saveButton)
                        .addComponent(cancelButton)
                        .addComponent(NewProgram)
                        .addComponent(DeleteProgram))
                    .addComponent(EditProgram, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void NewProgramActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NewProgramActionPerformed
       Program p = new Program();
       em.persist(p);      
       ProgramEdit pef = new ProgramEdit(null,true,p,em);
       pef.setTitle("Νέο Πρόγραμμα");
       pef.setVisible(true);
       if (pef.getReturnStatus() == ProgramEdit.RET_OK) {
           programList.add(p);
       } else {
           for (ProgramRate pr : p.getProgramRateList()) { 
                em.remove(pr);
           }
           em.remove(p);
       }
    }//GEN-LAST:event_NewProgramActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        try {
            //Ακύρωσε οποιαδήποτε αλλαγή στην Β.Δ.
            if (em.getTransaction().isActive()) {
                em.getTransaction().rollback();
            }
            //Κλείσε το τρέχον παράθυρο
            this.dispose();
        }
        catch (Exception ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        try {
            //Αποθήκευσε τις αλλαγές στην ΒΔ
            em.getTransaction().commit();
            //Κλείσε το τρέχον παράθυρο
            this.dispose();
        }
        catch (Exception ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }//GEN-LAST:event_saveButtonActionPerformed

    private void DeleteProgramActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DeleteProgramActionPerformed
        int s = programTable.getSelectedRow();
        if (s >= 0) {            
            Program p = programList.get(programTable.convertRowIndexToModel(s));
            // Επιβεβαίωση της διαγραφής
            if (p.getCardList().isEmpty()) {                
                // Επιβεβαίωση της διαγραφής
                int choice = JOptionPane.showConfirmDialog(this,
                                          "Διαγραφή του προγράμματος" + p.getName() + ";",
                                          "Επιβεβαίωση διαγραφής προγράμματος",
                                          JOptionPane.YES_NO_OPTION);
                if (choice != 0) {
                    return;
                }                
                try {
                    for (ProgramRate pr : p.getProgramRateList()) { 
                         em.remove(pr);
                    }
                    em.remove(p);
                    programList.remove(p);
                }
                catch (Exception ex) {
                    JOptionPane.showMessageDialog(this, ex.getMessage());
                }
            } else { 
                JOptionPane.showMessageDialog(this, "Το πρόγραμμα " + p.getName() + " δεν μπορεί να διαγραφεί (υπάρχουν οχήματα με το πρόγραμμα αυτό).",
                                          "Σφάλμα",JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_DeleteProgramActionPerformed

    private void EditProgramActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EditProgramActionPerformed
        int s = programTable.getSelectedRow();
        if (s>=0) {
            Program p = programList.get(s);
            //em.getTransaction().begin();
            ProgramEdit pef  = new ProgramEdit(null, true, p, em);
            pef.setTitle("Επεξεργασία Ρόλου: " + p.getName());
            pef.setVisible(true);
            if (pef.getReturnStatus() == ProgramEdit.RET_OK) {
                programList.set(s, p);
            } else {
                for (ProgramRate pr : p.getProgramRateList()) { 
                    em.refresh(pr);
                }
                em.refresh(p);
            }
        }
    }//GEN-LAST:event_EditProgramActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton DeleteProgram;
    private javax.swing.JButton EditProgram;
    private javax.swing.JButton NewProgram;
    private javax.swing.JButton cancelButton;
    private javax.swing.JScrollPane jScrollPane1;
    private java.util.List<Program> programList;
    private javax.persistence.Query programQuery;
    private javax.swing.JTable programTable;
    private javax.swing.JButton saveButton;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    private EntityManager em;
}
